package com.fzy.core;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import javax.servlet.ServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.Logger;
//import org.acegisecurity.context.SecurityContext;
//import org.acegisecurity.context.SecurityContextHolder;
//import org.apache.commons.lang.StringUtils;
//import com.fzy.core.acegi.UserDetailsImpl;

import com.fzy.core.entity.EntityId;

public class U {

	private static final Log log = LogFactory.getLog(U.class);
	
	private static BaseService baseService;

	public static final String DEFAULT_LIST_DELIMIT = ", ";

	public static final String DEFAULT_DATE_PATTERN = "yyyy-MM-dd";

	public static final String LONG_DATE_PATTERN = "yyyyMMddHHmmss";

	public static final String DAY_DATE_PATTERN = "yyyyMMdd";

	public static final SimpleDateFormat DEFAULT_DATE_FORMAT = new SimpleDateFormat(
			DEFAULT_DATE_PATTERN);
	public static final SimpleDateFormat LONG_DATE_FORMAT = new SimpleDateFormat(
			LONG_DATE_PATTERN);
	public static final SimpleDateFormat DAY_DATE_FORMAT = new SimpleDateFormat(
			DAY_DATE_PATTERN);

	
	public void setBaseService(BaseService baseService) {
		U.baseService = baseService;
	}

	public static BaseService getBaseService() {
		return baseService;
	}

	public static String number2string(long number, int length){
		String result = number + "";
		for (int i = result.length(); i < length; i++) {
			result = "0" + result;
		}
		return result;
	}
	
	public static Long getUser() {
//		UserDetailsImpl u = getCurrentUserdDetails();
//		if(u != null) return u.getId();
		return new Long(0);
	}

	public static String getUserString() {
//		UserDetailsImpl u = getCurrentUserdDetails();
//		if(u != null) return u.getUsername();
		return "0";
	}

	public static String getUserEmployeeName() {
//		UserDetailsImpl u = getCurrentUserdDetails();
//		if(u != null) return u.getEmployeeName();
		return "";
	}

//	public static UserDetailsImpl getCurrentUserdDetails() {
//		SecurityContext s = SecurityContextHolder.getContext();
//		if (s != null && s.getAuthentication() != null
//				&& s.getAuthentication().getPrincipal() != null) {
//			Object obj = s.getAuthentication().getPrincipal();
//			if (obj instanceof UserDetailsImpl) {
//				return (UserDetailsImpl) obj;
//			}
//		}
//		return null;
//	}

	/**
	 * 必须是 EntityId 或 IIdStringEntity 的 list
	 * 
	 * @param list
	 * @return
	 */
	public static List getIdList(List list) {
		List result = new ArrayList();
//		if (list == null || list.size() < 1)
//			return result;
//		for (Iterator iterator = list.iterator(); iterator.hasNext();) {
//			Object o = (Object) iterator.next();
//			if (o == null)
//				continue;
//			if (o instanceof IIdEntity) {
//				IIdEntity e = (IIdEntity) o;
//				result.add(e.getId());
//			} else if (o instanceof IIdStringEntity) {
//				IIdStringEntity e = (IIdStringEntity) o;
//				result.add(e.getId());
//			}
//		}
		return result;
	}

	public static String joinList(List list) {
		return joinList(list, null);
	}

	public static String joinList(List list, String delimit) {
		String result = "";
		if (list == null || list.size() < 1)
			return result;
		if (delimit == null)
			delimit = DEFAULT_LIST_DELIMIT;
		for (Iterator iterator = list.iterator();;) {
			Object object = (Object) iterator.next();
			result += (object == null ? "" : object.toString());
			if (iterator.hasNext()) {
				result += delimit;
			} else {
				return result;
			}
		}
	}

	public static String getDateString(String pattern) {
		return getDateString(pattern, -1, 0);
	}

	public static String getDateString(String pattern, int dateType, int offset) {
		Calendar c = Calendar.getInstance();
		if (dateType > 0 && offset != 0)
			c.add(dateType, offset);
		SimpleDateFormat sdf = new SimpleDateFormat(pattern);
		return sdf.format(c.getTime());
	}

	public static String parseDateToString(String src) {
		return parseDateSafely(src, DEFAULT_DATE_PATTERN, LONG_DATE_PATTERN);
	}

	public static String parseDateInVo(String src) {
		return parseDateSafely(src, LONG_DATE_PATTERN, DEFAULT_DATE_PATTERN);
	}

	public static Date parseDate(String src) {
		return parseDateSafely(src, DEFAULT_DATE_FORMAT);
	}

	public static Date parseDateEnd(String src) {
		Date result = null;
		Date d = parseDateSafely(src, DEFAULT_DATE_FORMAT);
		if (d != null) {
			Calendar c = Calendar.getInstance();
			c.setTime(d);
			c.add(Calendar.DATE, 1);
			result = c.getTime();
		}
		return result;
	}

	public static String parseDateEndToString(String src) {
		String result = null;
		Date d = parseDateEnd(src);
		if (d != null)
			result = LONG_DATE_FORMAT.format(d);
		return result;
	}

	public static String parseDateSafely(String src, String srcPattern,
			String targetPattern) {
		SimpleDateFormat srcFormat = new SimpleDateFormat(srcPattern);
		SimpleDateFormat targetFormat = new SimpleDateFormat(targetPattern);
		return parseDateSafely(src, srcFormat, targetFormat);
	}

	public static Date parseDateSafely(String src, SimpleDateFormat srcFormat) {
		Date result = null;
		if (!StringUtils.isBlank(src)) {
			try {
				result = srcFormat.parse(src);
			} catch (ParseException e) {
				log.error("format date error:", e);
			}
		}
		return result;
	}

	public static String parseDateSafely(String src,
			SimpleDateFormat srcFormat, SimpleDateFormat targetFormat) {
		String result = null;
		Date d = parseDateSafely(src, srcFormat);
		if (d != null)
			result = targetFormat.format(d);
		return result;
	}

	public static void copyProperties(Object target, Object source)
			throws IllegalArgumentException, IllegalAccessException {
		if (target == null || source == null)
			return;

		List destFields = getFields(target.getClass());
		List origFields = getFields(source.getClass());

		Object origValue = null;
		Field origField = null;
		String origName = null;
		String origType = null;
		Field destField = null;
		String destName = null;
		String destType = null;

		for (Iterator iterator = origFields.iterator(); iterator.hasNext();) {
			origField = (Field) iterator.next();
			origName = origField.getName();
			origType = origField.getType().getName();
			for (Iterator iterator2 = destFields.iterator(); iterator2
					.hasNext();) {
				destField = (Field) iterator2.next();
				destName = destField.getName();
				destType = destField.getType().getName();
				if (origName.equals(destName) && origType.equals(destType)) {
					origField.setAccessible(true);
					destField.setAccessible(true);
					origValue = origField.get(source);
					destField.set(target, origValue);
				}
			}
		}
	}

	public static void copyPropertiesSafely(Object target, Object source) {
		try {
			copyProperties(target, source);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
	}

	public static Long parseLongSafely(String value) {
		if (value == null) {
			return null;
		}

		try {
			return new Long(value);
		} catch (NumberFormatException e) {
			return null;
		}
	}

	public static Integer parseIntegerSafely(String value) {
		if (value == null) {
			return null;
		}

		try {
			return new Integer(value);
		} catch (NumberFormatException e) {
			return null;
		}
	}

	public static Double parseDoubleSafely(String value) {
		if (value == null) {
			return null;
		}

		try {
			return new Double(value);
		} catch (NumberFormatException e) {
			return null;
		}
	}

	public static int parseIntSafely(String src, int defaultValue) {
		Integer i = parseIntegerSafely(src);
		if (i == null)
			return defaultValue;
		return i.intValue();
	}

	public static long parseLongSafely(String src, long defaultValue) {
		Long l = parseLongSafely(src);
		if (l == null)
			return defaultValue;
		return l.longValue();
	}

	public static boolean isCollectionEmpty(Collection c) {
		return c == null ? true : c.isEmpty();
	}

	public static boolean isArrayEmpty(Object[] c) {
		return c == null || c.length < 1;
	}

	public static Long getRsLong(String name, ResultSet rs) throws SQLException {
		Long result = null;
		BigDecimal v = rs.getBigDecimal(name);
		if (v != null)
			result = new Long(v.longValue());
		return result;
	}

	public static Double getRsDouble(String name, ResultSet rs)
			throws SQLException {
		Double result = null;
		BigDecimal v = rs.getBigDecimal(name);
		if (v != null)
			result = new Double(v.doubleValue());
		return result;
	}

	public static Object getFieldValue(final Object obj, final String fieldName) {
		Field field = getField(obj.getClass(), fieldName);
		if (field != null) {
			field.setAccessible(true);
			try {
				return field.get(obj);
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	public static void setFieldValue(final Object obj, final String fieldName, final Object value) {
		Field field = getField(obj.getClass(), fieldName);
		if (field != null) {
			field.setAccessible(true);
			try {
				field.set(obj, value);
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}
	}

	public static Map getParameters(ServletRequest request) {
		Map params = new TreeMap();
		if (request == null)
			return params;
		Enumeration paramNames = request.getParameterNames();
		while (paramNames != null && paramNames.hasMoreElements()) {
			String paramName = (String) paramNames.nextElement();
			String[] values = request.getParameterValues(paramName);
			if (values == null || values.length == 0) {
				// Do nothing, no values found at all.
			} else if (values.length > 1) {
				params.put(paramName, values);
			} else {
				params.put(paramName, values[0]);
			}
		}
		return params;
	}

	public static List getFields(Class objClass) {
		List result = new ArrayList();
		for (Class superClass = objClass; superClass != Object.class; superClass = superClass
				.getSuperclass()) {
			Field[] fields = superClass.getDeclaredFields();
			addFieldsToList(fields, result);
		}
		return result;
	}

	private static void addFieldsToList(Field[] fields, List list) {
		if (fields == null || list == null)
			return;
		for (int i = 0; i < fields.length; i++) {
			Field f = fields[i];
			String fieldName = f.getName();
			boolean isInList = false;
			for (Iterator iterator = list.iterator(); iterator.hasNext();) {
				Field field = (Field) iterator.next();
				if (fieldName.equals(field.getName())) {
					isInList = true;
					break;
				}
			}
			if (!isInList)
				list.add(f);
		}
	}

	public static Field getField(Class objClass, final String fieldName) {
		for (Class superClass = objClass; superClass != Object.class; superClass = superClass
				.getSuperclass()) {
			try {
				Field field = superClass.getDeclaredField(fieldName);
				return field;
			} catch (NoSuchFieldException e) {// NOSONAR
			}
		}
		return null;
	}

	public static String null2string(Object src) {
		return src == null ? "" : src.toString();
	}

}
